# -*- coding: utf-8 -*-
"""包括问答、评论、咨询、反馈"""

import datetime
import time

from flask import request, g, current_app, abort
from mongoengine import Q

from app.constants import user_agents, DEVICE_TYPES, ORDER_REMIND_EMAILS
from app.controllers import (
    get_user_agent, api_paginate_queryset, get_object_or_404,
    get_mtu_comments,
)
from app.forms import SupportConsultationForm, FeedbackForm
from app.models import (
    Feedback, DeviceId, Mtu, MtuComment, MtuDialog,
    UserPlan, Order)
from app.utils import (
    api_error, trim, get_objectId, wrap_response,
    safe_int, safe_float, send_email, send_staff_dialog_email)
from app.third_party_api import btapi


@current_app.route("/vacation/support/consultation/", methods=["POST"])
def consultation():
    # 咨询
    """
        咨询

        #### 请求参数

        参数名 | 必需 | 类型 | 说明
        ---- | ---- | ---- | ----
        name | Y | str | 略
        tel | Y | str | 略

        #### 返回结果
        {}
    """
    if request.form:
        params = request.form
    else:
        params = request.json

    device_id = request.headers.get('HTTP_VACATION_DEVICE_ID')
    name = trim(params.get('name'))
    tel = trim(params.get('tel'))

    if not device_id:
        return api_error(49999, msg=u"非法请求", detail=u"缺少DeviceId")

    form = SupportConsultationForm(params)
    if form.validate():
        user_agent = get_user_agent(request)
        if user_agent == user_agents.ANDROID:
            device = DEVICE_TYPES.ANDROID
        else:
            device = DEVICE_TYPES.IOS

        obj = DeviceId.objects(device_id=device_id,
                               device=device).modify(upsert=True,
                                                     new=True,
                                                     set__device_id=device_id,
                                                     set__device=device)

        obj.name = name
        obj.tel = name
        obj.consultation_date = datetime.datetime.now()
        obj.save()

        # api_v2 可以修改 提前到 device_id 判断之后
        condition = Q(is_active=True, device_id=device_id)
        plan = UserPlan.objects.filter(condition).first()
        if not plan:
            return wrap_response({})

        title = u'用户咨询（24小时内回复）'
        if plan.app_data:
            prefix = 'http://vacation.breadtrip.com/share/plan/%s/itinerary/'
            url = prefix % plan.share_id
        else:
            url = u'没有完成行程'
        mail_body_prefix = u'-称呼:%s\n\n-手机号:%s\n\n-完整行程单链接:%s\n\n'
        mail_body = mail_body_prefix % (name, tel, url)

        # tasks.send_email.delay(title, mail_body, ORDER_REMIND_EMAILS,
        #                            content_subtype='text', send_seperately=False)
        send_email(title, mail_body, ORDER_REMIND_EMAILS)
        return wrap_response({})
    else:
        errors = {}
        for key, value in form.errors.iteritems():
            errors[getattr(form, key).label.text] = value[0]

        return wrap_response({
            "code": 49999,
            "message": errors.items()
        })


@current_app.route("/vacation/support/feedback/", methods=['POST'])
def feedback():
    """
        反馈

        #### 请求参数

        参数名 | 必需 | 类型 | 说明
        ---- | ---- | ---- | ----
        email | Y | str | 略
        content | Y | str | 略

        #### 返回结果
        {}
    """
    if request.form:
        params = request.form
    else:
        params = request.json

    form = FeedbackForm(params)
    if form.validate():
        obj = dict(
            email=trim(params.get('email')),
            content=trim(params.get('content'))
        )
        Feedback.objects.create(**obj)
        return wrap_response({})
    else:
        errors = {}
        for key, value in form.errors.iteritems():
            errors[getattr(form, key).label.text] = value[0]

        return wrap_response({
            "code": 49999,
            "message": errors.items()
        })


@current_app.route("/vacation/mtu/<mtu_id>/dialog/count/", methods=["GET"])
def mtu_dialog_counts(mtu_id):
    """
    MTU 问答数量

    #### 请求参数
    参数名 | 必须 | 类型 | 说明
    ---- | ---- | ---- | ----
    无 | 无 | 无| 无

    #### 返回结果

        {
            'count': 4,
        }
    """
    condition = Q(mtu_id=mtu_id, is_active=True)
    count = MtuDialog.objects.filter(condition).count()
    return wrap_response(dict(count=count))


@current_app.route("/vacation/mtu/<mtu_id>/dialogs/", methods=["GET"])
def mtu_dialogs(mtu_id):
    """
    用户Mtu 问答详细

    #### 请求参数
    参数名 | 必须 | 类型 | 说明
    ---- | ---- | ---- | ----
    start | N | int | 开始
    count | N | int | 数量

    #### 返回结果
    {
        items: [
            {
                'text': xxxxx,
                'user': {
                    'avatar': ...,
                    'name': ...,
                },
                'date_added': '2014-11-20 12:23:12',
            }
        ]
    }
    """
    getter = request.args.get
    count = getter('count', 20, type=int)
    mtu_id = get_objectId(mtu_id)
    if not mtu_id:
        return wrap_response(dict(
            items=[],
            next_start=0,
        ))

    condition = Q(mtu=mtu_id, is_active=True)
    query_dialogs = MtuDialog.objects.filter(condition).order_by('-date_added')
    dialogs, next_start = api_paginate_queryset(request, query_dialogs)

    user_ids = [x.user_id for x in dialogs]
    user_ids = ','.join(user_ids)
    user_info_list = btapi.get_user_infos(user_ids)

    items = []
    for dialog in reversed(list(dialogs[:count])):
        items.append({
            'text': dialog.text,
            'date_added': int(time.mktime(dialog.date_added.timetuple())),
            'user': user_info_list.get(dialog.user_id, {})
        })

    data = dict(items=items, next_start=next_start)
    return wrap_response(data)


@current_app.route("/vacation/mtu/<mtu_id>/dialogs", methods=["POST"])
# @api_login_required
def add_mtu_dialog(mtu_id):
    """
    创建问答

    #### 请求参数
    参数名 | 必须 | 类型 | 说明
    ---- | ---- | ---- | ----
    text | Y | str | 用户发送内容

    #### 返回结果
    {}
    """
    args = request.form

    text = trim(args.get('text', ''))
    if not text:
        abort(404)

    mtu = get_object_or_404(Mtu, mtu_id)

    obj = dict(
        user=safe_int(g.current_user.id),
        mtu=mtu.id,
        text=text,
    )
    dialog = MtuDialog.objects.create(**obj)

    # e = EmailManage()
    # e.send_staff_dialog_email(mtu.name(), request.user.username, text,
    #                           dialog.date_added.strftime('%Y-%m-%d %H:%M:%S'))
    send_staff_dialog_email(
        mtu.name(),
        g.current_user.username,
        text,
        dialog.date_added.strftime('%Y-%m-%d %H:%M:%S')
    )
    return wrap_response({})


@current_app.route("/vacation/mtu/<mtu_id>/comment/", methods=["GET"])
def mtu_comments(mtu_id):
    """
    mtu 评论

    #### 请求参数
    参数名 | 必须 | 类型 | 说明
    ---- | ---- | ---- | ----
    start | N | int | tips起始值，默认为0。
    count | N | int | tips数，默认为20。
    is_encrypt | N | boolean | 是否加密, 默认时true，离线数据传false

    #### 返回结果
    {
        "next_start":  20,                             // 判断是否翻页
        "tips": [
            {
                "id": 2450924544,
                "user": {
                    "id": 1234567890,
                    "name": 灰太狼,
                    "avatar_s": "avatars/jimmy/resized/25/avatars/...",
                    "avatar_m": "avatars/jimmy/resized/46/avatars/...",
                    "avatar_l": "avatars/jimmy/resized/46/avatars/...",
                    "custom_url": "",
                    "cover": ""
                },
                "content": "xxx是世界上降水量较多的地区",   // 相关内容
                "datetime": "2013-06-15 18:30",            // 日期时间
                "liked_count": "234",                      // 被赞数量
                "liked": true or false                     // 是否赞过tips
                "trip_id": 2343543435,                     // 旅程id
                "socre": 0,                               //评分
            },
            ...
        ]
    }

    """
    args = request.args
    start = args.get('start', 0, type=int)
    count = args.get('count', 20, type=int)

    mtu = get_object_or_404(Mtu, mtu_id)
    ret = get_mtu_comments(mtu, start, count)

    return wrap_response(data=ret)


@current_app.route("/vacation/mtu/<mtu_id>/comment/add/", methods=["POST"])
# @api_login_required
def add_mtu_comment(mtu_id):
    """
    为mtu添加一个comment

    #### 请求参数

    参数名 | 必需 | 类型 | 说明
    ----   | ---- | ---- | ----
    content | Y | int | tip内容
    order_id | N | int | 订单ID
    rating | N | float | 评分

    #### 返回结果

    {
        "id": 2384501041,                                   // Tip 的id
        "content": '',                                      // 内容
        "datetime": "2013-07-18 11:45",                     // 时间
        "rating": 0,                                         // tip的评分
    }

    """
    getter = request.form.get
    mtu = get_object_or_404(Mtu, mtu_id)

    rating = safe_float(getter('rating'))
    if rating > 5.0 or rating <= 0:
        return api_error(40611)

    content = trim(getter('content', ''))
    if not content:
        return api_error(49999)

    obj = dict(
        mtu=mtu,
        text=content,
        score=rating,
        user=g.current_user.id
    )
    mtu_comment = MtuComment.objects.create(**obj)

    order_id = safe_int(getter('order_id', 0))
    order = Order.objects.filter(id=order_id).first()
    ret = {
        'id': str(mtu_comment.id),
        'content': content,
        'datetime': mtu_comment.date_added.strftime('%Y-%m-%d %H:%M;%S'),
        'rating': rating,
    }
    if order:
        order.is_tipped = True
        order.save()
        ret.update(is_tipped=True)

    return wrap_response(data=ret)
